package cn.yuanqiao.web.controller.archive.archiveBorrowCar;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.archive.archiveBorrow.domain.YqDaBorrow;
import cn.yuanqiao.archive.archiveBorrow.domain.YqdaborrowItem;
import cn.yuanqiao.archive.archiveBorrow.mapper.YqDaBorrowMapper;
import cn.yuanqiao.archive.archiveBorrow.service.IYqDaBorrowService;
import cn.yuanqiao.archive.archiveFormSave.domain.YqdaArchiveForm;
import cn.yuanqiao.archive.common.util.SplitArchiveList;
import cn.yuanqiao.archive.liyong.mapper.AppointmentFormMapper;
import cn.yuanqiao.archive.xiaoxitongzhi.service.IYqXxtzService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.system.service.ISysUserService;
import cn.yuanqiao.common.core.domain.entity.SysDept;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.archiveBorrowCar.domain.YqdaborrowCar;
import cn.yuanqiao.archive.archiveBorrowCar.service.IYqdaborrowCarService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * archiveBorrowCarController
 * 
 * @author yuanqiao
 * @date 2023-07-14
 */
@RestController
@RequestMapping("/archive/archiveBorrowCar")
public class YqdaborrowCarController extends BaseController
{
    @Autowired
    private IYqdaborrowCarService yqdaborrowCarService;

    @Resource
    private RemoteActivitiService remoteActivitiService;
    

    @Autowired
    private YqDaBorrowMapper yqDaBorrowMapper;

    @Autowired
    private SplitArchiveList splitArchiveList;

    @Autowired
    private IYqDaBorrowService yqDaBorrowService;

    @Autowired
    private IYqXxtzService yqXxtzService;
    @Autowired
    private AppointmentFormMapper appointmentFormMapper;


    /**
     * 查询archiveBorrowCar列表
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:list')")
    @GetMapping("/list")
    public TableDataInfo list(YqdaborrowCar yqdaborrowCar)
    {
        startPage();
        List<YqdaborrowCar> list = yqdaborrowCarService.selectYqdaborrowCarList(yqdaborrowCar);
        return getDataTable(list);
    }

    /**
     * 导出archiveBorrowCar列表
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:export')")
    @Log(title = "archiveBorrowCar", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqdaborrowCar yqdaborrowCar)
    {
        List<YqdaborrowCar> list = yqdaborrowCarService.selectYqdaborrowCarList(yqdaborrowCar);
        ExcelUtil<YqdaborrowCar> util = new ExcelUtil<>(YqdaborrowCar.class);
        util.exportExcel(response, list, "archiveBorrowCar数据");
    }

    /**
     * 获取archiveBorrowCar详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:query')")
    @GetMapping(value = "/{carId}")
    public AjaxResult getInfo(@PathVariable("carId") String carId)
    {
        return success(yqdaborrowCarService.selectYqdaborrowCarByCarId(carId));
    }

    @GetMapping("/getArchiveList")
    public AjaxResult getArchiveList( YqdaborrowCar yqdaborrowCar)
    {
        List<Map<String, Object>> list = yqdaborrowCarService.getArchiveListByArchiveCategory(yqdaborrowCar);
        return AjaxResult.success("查询成功",list);
    }

    /**
     * 新增archiveBorrowCar
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:add')")
    @Log(title = "archiveBorrowCar", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqdaborrowCar yqdaborrowCar)
    {
        yqdaborrowCar.setTenantCode(SecurityUtils.getTenantCode());
        return toAjax(yqdaborrowCarService.insertYqdaborrowCar(yqdaborrowCar));
    }

    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:add')")
    @Log(title = "archiveBorrowCar", businessType = BusinessType.INSERT)
    @PostMapping("/batchInsert")
    public AjaxResult batchInsert(@RequestBody List<YqdaborrowCar> yqdaborrowCars){
        String batchNo = String.valueOf(SnowflakeIdGenerator.generateId());
        StringBuilder ids = new StringBuilder();
        String userId = String.valueOf(SecurityUtils.getUserId());
        AtomicBoolean checkFlag = new AtomicBoolean(false);
        yqdaborrowCars.forEach(form -> {
            form.setCarId(String.valueOf(SnowflakeIdGenerator.generateId()));
            form.setTenantCode(SecurityUtils.getTenantCode());
            form.setUserId(userId);
            form.setSTATUS("1");
            form.setBorrowType("1");
            //FIXME 档案类型
            if (form.getDaType() == null) {
                form.setDaType("E");
            } else {
                form.setDaType("1".equals(form.getDaType())?"E":"F");
            }
            form.setAddTime(DateUtils.getNowDate());
            form.setTenantCode(SecurityUtils.getTenantCode());
            if (form.getDaId()==null||form.getDaId().equals("")||form.getCategoryId()==null||form.getCategoryId().equals("")) checkFlag.set(true);
        });
        if (checkFlag.get()){
            return AjaxResult.error("档案ID或者门类ID为空，不允许添加");
        }

        if (yqdaborrowCarService.checkArchiveIsAddCar(yqdaborrowCars)){
            return AjaxResult.error("已经添加到借阅车的数据不能再次添加");
        }

        int result = yqdaborrowCarService.batchInsertYqdaborrowCar(yqdaborrowCars);
        return AjaxResult.success(result);
    }

    /**
     * 新增archiveBorrowCar
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:submit')")
    @Log(title = "archiveBorrowCar", businessType = BusinessType.BORROW)
    @PostMapping("/submit/{carIds}")
    public AjaxResult submit(@PathVariable("carIds")  String[] carIds,@RequestBody YqDaBorrow yqdaborrowData)
    {
        YqdaborrowCar yqdaborrowCar = new YqdaborrowCar();
        yqdaborrowCar.setCarIds(carIds);
        yqdaborrowCar.setUserId(String.valueOf(SecurityUtils.getUserId()));
        yqdaborrowCar.setTenantCode(SecurityUtils.getTenantCode());
        List<YqdaborrowCar> list = yqdaborrowCarService.selectYqdaborrowCarList(yqdaborrowCar);
        boolean judgeborrow = yqdaborrowCarService.judgeborrow(list);
        if (judgeborrow){
            throw new ServiceException("当前档案已经被借阅或者预约!");
        }
        /*ListQuery listQuery*/
        StringBuilder ids = new StringBuilder();
        for (String carId : carIds) {
            ids.append(carId).append(",");
        }//(item->{ids.append(item.getDaId()).append(",");});\
        Map<Long,List<String>> archiveCateMap = new HashMap<>();
        Map<String,String> daTypeMap = new HashMap<>();
        for (YqdaborrowCar carItem : list) {
            daTypeMap.put(carItem.getDaId(),carItem.getDaType());
            if (ids.toString().contains(carItem.getDaId())){
                if (archiveCateMap.get(carItem.getCategoryId()) == null){
                    List<String> daIdsList = new ArrayList<>();
                    daIdsList.add(carItem.getDaId());
                    archiveCateMap.put(carItem.getCategoryId(),daIdsList);
                }else {
                    archiveCateMap.get(carItem.getCategoryId()).add(carItem.getDaId());
                }
            }
        }
        ids.deleteCharAt(ids.length()-1);
        List<Map<String,Object>> archiveLists = yqdaborrowCarService.selectArchiveByArchiveIdAndCategoryIdMap(archiveCateMap);
        archiveLists.forEach(item->item.put("archive_site_view",yqdaborrowData.getBranchCode()));
        /**
         *          FormProperty_3qipis2--__!!radio--__!!审批意见--__!!i--__!!同意--__--不同意
         *          FormProperty_0lffpcm--__!!textarea--__!!批注--__!!f__!!null
         *
         */
        R<String> borrowForm = remoteActivitiService.getFormCodeByBusinessKey("WorkFlow_Archive_Borrow", SecurityUtils.getTenantCode());
        Map<String, Map<String, Object>> splitArchiveByFormCode = splitArchiveList.splitArchiveByFormCodeNew(borrowForm.getData(), archiveLists);
        int size = splitArchiveByFormCode.size();
        int count = 0;
        for (Map.Entry<String, Map<String, Object>> entry:splitArchiveByFormCode.entrySet()){
            Map<String, Object> item = entry.getValue();
            if (entry.getKey().equals("notConditionValue")){
                count++;
                continue;
            }
            System.out.println(111);
            YqDaBorrow yqDaBorrow = new YqDaBorrow();
            BeanUtils.copyProperties(yqdaborrowData,yqDaBorrow);
            yqDaBorrow.setBorrowId(SnowflakeIdGenerator.generateId());
            yqDaBorrow.setCreater(SecurityUtils.getUserId());
            yqDaBorrow.setStatus(4);
            yqDaBorrow.setTenantCode(SecurityUtils.getTenantCode());
            Map<String, Object> map = yqDaBorrow.toProcessMap();
            item.put("processVariables",map);
            item.put("archive_site_view",yqdaborrowData.getBranchCode());
/*            item.put("archive_has_mj","1");
            item.put("archive_is_dept","1");
            item.put("archive_site_view","1");
            item.put("archive_type","lt");*/
            String elCorn = entry.getKey();

            R<ActivitiPackage> activitiPackageR = remoteActivitiService.startProcessWsArchiveBorrow(item);
            yqDaBorrow.setProcessId(activitiPackageR.getData().getProcessInstance().getId());
            List<YqdaborrowItem> yqdaborrowItems = new ArrayList<>();
            List<Map<String,Object>> archiveData = (List<Map<String,Object>>)item.get("archiveData");

            List<String > archiveIds = new ArrayList<>();
            boolean allEfile = true;
            boolean allFfile = true;
            if (archiveData.size()==0){
                allEfile = false;
                allFfile = false;
            }
            for (Map<String, Object> archive : archiveData) {
                archiveIds.add(String.valueOf(archive.get("ID")));
                YqdaborrowItem yqdaborrowItem = new YqdaborrowItem();
                yqdaborrowItem.setItemId(String.valueOf(SnowflakeIdGenerator.generateId()));
                yqdaborrowItem.setBorrowId(yqDaBorrow.getBorrowId());
                yqdaborrowItem.setDaId(String.valueOf(archive.get("ID")));
                yqdaborrowItem.setCategoryId((Long)archive.get("CATEGORY_ID"));
                yqdaborrowItem.setIsBenchu("0");
                yqdaborrowItem.setSubTableName(String.valueOf(archive.get("SUB_TABLE_NAME")));
                yqdaborrowItem.setStatus("4");
                yqdaborrowItem.setFeedBack(String.valueOf(archive.get("DA_TYPE")));
                String daType = daTypeMap.get(String.valueOf(archive.get("ID")));
                String state = "";
                /*if ("0".equals(daType)){
                    allEfile = false;
                    state = "0";
                }else {
                    allFfile = false;
                    state = "1";
                }*/
                if ("F".equals(daType)){
                    allEfile = false;
                    state = "0";
                }else {
                    allFfile = false;
                    state = "1";
                }
                yqdaborrowItem.setState(state);
                yqdaborrowItem.setDownloadable(yqdaborrowData.getAllowDownload());
                if ("1".equals(yqdaborrowData.getAllowDownload())){
                    yqdaborrowItem.setDownloadCount(yqdaborrowData.getDownloadNum());
                    yqdaborrowItem.setPermitDownloadCount(yqdaborrowData.getDownloadNum());
                }
                yqdaborrowItem.setPrintable(yqdaborrowData.getAllowPrint());
                if ("1".equals(yqdaborrowData.getAllowPrint())){
                    yqdaborrowItem.setPrintCount(Integer.valueOf(yqdaborrowData.getPrintNum()));
                }
                yqdaborrowItem.setBorrowUserId(String.valueOf(SecurityUtils.getUserId()));
                yqdaborrowItems.add(yqdaborrowItem);

            }
            List<String> idsList = new ArrayList<>();
            for (String archiveId : archiveIds) {
                for (YqdaborrowCar borrowCar : list) {
                    if (archiveId.equals(borrowCar.getDaId())){
                        idsList.add(borrowCar.getCarId());

                    }
                }
            }
            String[] idsArray = new String[idsList.size()];
            yqdaborrowCarService.deleteYqdaborrowCarByCarIds(idsList.toArray(carIds));
            yqDaBorrow.setYqdaborrowItemList(yqdaborrowItems);
            /*//FIXME 档案类型
            yqDaBorrow.setDaType("E");*/
            //yqDaBorrow.setDaType(allFfile?"F":allEfile?"E":"A");
            yqDaBorrowService.insertYqDaBorrow(yqDaBorrow);
            if ("F".equals(yqDaBorrow.getDaType())&&"2".equals(yqDaBorrow.getLiyongfangshi())){
                //update stjsfjc
                for (YqdaborrowItem yqdaborrowItem : yqdaborrowItems) {
                    String daId = yqdaborrowItem.getDaId();
                    String subTableName = yqdaborrowItem.getSubTableName();
                    Long categoryId = yqdaborrowItem.getCategoryId();
                    Map<String, Object> category = yqDaBorrowMapper.selectCategory(SecurityUtils.getTenantCode().toUpperCase() + "_CATEGORY", categoryId);
                    String fileTableName = String.valueOf(category.get("FILE_TABLE_NAME"));
                    String folderTableName = String.valueOf(category.get("FOLDER_TABLE_NAME"));
                    String itemTableName = String.valueOf(category.get("ITEM_TABLE_NAME"));

                    String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
                    if (subTableName.equals(fileTableName)){
                        yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",subTableName,"1",daId);
                    }else if (subTableName.equals(folderTableName)){
                        yqDaBorrowMapper.updateArchiveSFJCNew("FOLDER_ID",tenantCode+"_YQFOLDER",subTableName,"1",daId);
                        yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",fileTableName,"1","SELECT DA_ID FROM "+tenantCode+"_YQDA_FOLDER WHERE FOLDER_ID ='" +daId+"'");
                    }else if (subTableName.equals(itemTableName)){
                        yqDaBorrowMapper.updateArchiveSFJCNew("ITEM_ID",tenantCode+"_YQITEM",subTableName,"1",daId);
                        yqDaBorrowMapper.updateArchiveSFJCNew("FOLDER_ID",tenantCode+"_YQFOLDER",folderTableName,"1","SELECT FOLDER_ID FROM "+tenantCode+"_ITEM_FOLDER WHERE ITEM_ID ='" +daId+"'");
                        yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",fileTableName,"1","SELECT DA_ID FROM "+tenantCode+"_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM "+tenantCode+"_ITEM_FOLDER WHERE ITEM_ID ='" +daId+"')");
                    }
                }
            }
        }

        return AjaxResult.success("您的申请单已经根据审批流程被分为"+(size-count)+"份申请提交");
    }

    /**
     * 修改archiveBorrowCar
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:edit')")
    @Log(title = "archiveBorrowCar", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqdaborrowCar yqdaborrowCar)
    {
        return toAjax(yqdaborrowCarService.updateYqdaborrowCar(yqdaborrowCar));
    }

    /**
     * 删除archiveBorrowCar
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:remove')")
    @Log(title = "archiveBorrowCar", businessType = BusinessType.DELETE)
    @DeleteMapping("/{carIds}")
    public AjaxResult remove(@PathVariable String[] carIds)
    {
        return toAjax(yqdaborrowCarService.deleteYqdaborrowCarByArchiveIds(carIds));
    }

    /**
     * 删除archiveBorrowCar
     */
    @Log(title = "archiveBorrowCar", businessType = BusinessType.DOWNLOAD)
    @GetMapping("/downloadPurchaseRecordForm")
    public ResponseEntity<byte[]> downloadPurchaseRecordForm() throws IOException {

        //return toAjax(yqdaborrowCarService.deleteYqdaborrowCarByArchiveIds(carIds));
        // 从resources目录下获取文件
        ClassPathResource classPathResource = new ClassPathResource("borrowModel/purchaseRecordForm.docx");

        // 读取文件流

        InputStream inputStream = classPathResource.getInputStream();
        byte[] fileData = new byte[inputStream.available()];
        inputStream.read(fileData);

        // 设置响应头，指定文件名
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "资料采购计划及验证记录.docx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 创建 ResponseEntity 并返回文件流
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(fileData, headers, HttpStatus.OK);
        return responseEntity;
    }

    /**
     * 查询archiveBorrowCar列表
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:list')")
    @GetMapping("/startBorrowProcess")
    public TableDataInfo startBorrowProcess(YqdaborrowCar yqdaborrowCar)
    {
        yqdaborrowCar.setUserId(String.valueOf(SecurityUtils.getUserId()));
        List<YqdaborrowCar> list = yqdaborrowCarService.selectYqdaborrowCarList(yqdaborrowCar);
        /*ListQuery listQuery*/
        StringBuilder ids = new StringBuilder();
        list.stream().forEach(item->{ids.append(item.getDaId()).append(",");});
        ids.deleteCharAt(ids.length()-1);
        List<Map<String,Object>> archiveLists = yqdaborrowCarService.selectArchiveByArchiveIdAndCategoryId(ids.toString());
        List archiveList = new ArrayList<>();
        Map<String,Map<String, Object>> splitArchiveByFormCode = splitArchiveList.splitArchiveByFormCodeNew("YQDA", archiveLists);
        for (Map.Entry<String, Map<String, Object>> entry:splitArchiveByFormCode.entrySet()){
            Map<String, Object> item = entry.getValue();
            if (entry.getKey().equals("notConditionValue")){
                continue;
            }
            remoteActivitiService.startProcessWsArchiveBorrow(item);
            System.out.println(111);
            YqDaBorrow yqDaBorrow = new YqDaBorrow();
            yqDaBorrow.setBorrowId(SnowflakeIdGenerator.generateId());
            yqDaBorrow.setBorrowUser(SecurityUtils.getUserId());
            yqDaBorrow.setStatus(0);
            List<YqdaborrowItem> yqdaborrowItems = new ArrayList<>();
            List<Map<String,Object>> archiveData = (List<Map<String,Object>>)item.get("archiveData");
            for (Map<String, Object> archive : archiveData) {
                YqdaborrowItem yqdaborrowItem = new YqdaborrowItem();
                yqdaborrowItem.setItemId(String.valueOf(SnowflakeIdGenerator.generateId()));
                yqdaborrowItem.setBorrowId(yqDaBorrow.getBorrowId());
                yqdaborrowItem.setDaId(String.valueOf(archive.get("ID")));
                //yqdaborrowItem.setMiji(String.valueOf(archive.get("MJ")));
                yqdaborrowItem.setState("0");
                yqdaborrowItems.add(yqdaborrowItem);
            }
            yqDaBorrow.setYqdaborrowItemList(yqdaborrowItems);
            yqDaBorrowService.insertYqDaBorrow(yqDaBorrow);
        }

        return getDataTable(list);
    }

    /**
     * 档案催还
     * @param msg
     * @return
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrowCar:cuiHuanBtn')")
    @PostMapping("/cuiHuan/{id}")
    public AjaxResult cuihuan(@PathVariable("id") Long id,@RequestBody JSONObject msg){
        yqDaBorrowService.cuihuan(id,msg.getString("msg"));
        return AjaxResult.success();
    }
}
